package cn.edu.suda.schoolBus.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;

		String uri = request.getRequestURI();
		String adminUserAccount = (String) request.getSession().getAttribute("adminUserAccount");

		if (uri.startsWith("/schoolBus/resources/")) {
			filterChain.doFilter(request, response);
		} else {
			if (uri.startsWith("/schoolBus/client/")) {
				filterChain.doFilter(request, response);
			} else {
				if (uri.indexOf("/schoolBus/mLogin") > -1) {
					if (adminUserAccount != null) {
						response.sendRedirect("/schoolBus/mHome");
					} else {
						filterChain.doFilter(request, response);
					}
				} else if (uri.equals("/schoolBus/adminUserLogin")) {
					filterChain.doFilter(request, response);
				} else {
					if (adminUserAccount == null) {
						response.sendRedirect("/schoolBus/mLogin");
					} else {
						filterChain.doFilter(request, response);
					}
				}
			}
		}

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
